<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use common\models\FileObj;
use common\models\SensorVersion;
use common\models\Alert;
use common\models\Logger;
use common\models\Config;

use yii\helpers\ArrayHelper;





/**
 * Email controller
 */
class EmailController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        if(Config::getLicense()['sensorNowCount'] == 0){
            $rules = [];
        }else{
            $rules = [
                [
                    'actions' => [''],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                [
                    'actions' => ['get'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    'actions' => [],
                    'allow' => true,
                    'roles' => ['admin'],
                ],
            ];
        }
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['test', 'save','get'],
                'rules' => $rules,
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    // 'logout' => ['post'],
                    // 'test' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        $this->isAPI();
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public $enableCsrfValidation = false;

    private function isAPI(){
        $headers = Yii::$app->request->headers;
        if(stristr($headers['accept'],'application/json') !== false)
        {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        }else
        {
            Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        }
    }

    public function actionGet()
    {
        $data = Config::getEmail();
        $data['status'] = 'success';
        return $data;
    }

    public function actionSave()
    {
        if(!Yii::$app->request->isPost)
        {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        if(Yii::$app->request->isPost)
        {
            $RawBody = trim(Yii::$app->request->getRawBody());
            $post = json_decode($RawBody,true);
        }
        if(empty($post))
        {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Rawbody not JSON.';
            return $data;
        }
        Config::setEmail($post);
        $data['status'] = 'success';
        return $data;
    }

    public function actionTest()
    {
        if(!Yii::$app->request->isPost)
        {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        if(Yii::$app->request->isPost)
        {
            $RawBody = trim(Yii::$app->request->getRawBody());
            $post = json_decode($RawBody,true);
        }
        if(empty($post))
        {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Rawbody not JSON.';
            return $data;
        }


        $transport = [ 
            'class' => 'Swift_SmtpTransport', 
            'host' => $post['host'], 
            'username' => $post['username'], 
            'password' => $post['password'], 
            'port' => $post['port'], 
            'encryption' => $post['encryption'], 
        ];
        Yii::$app->mailer->setTransport($transport);
        $mail= Yii::$app->mailer->compose();
        $mail->setFrom($post['username']);
        $mail->setTo($post['alertEmail']);  
        $mail->setSubject("测试邮件");  
        $mail->setHtmlBody("恭喜您，你的邮箱设置是正确的！");

        try {
            $flag = $mail->send();
        } catch (Exception $e) {
            echo $e->getMessage();
            $flag = false;
        }
        if($flag)  
            $data['status'] = 'success';
        else  
            $data['status'] = 'fail';
            $data['errorMessage'] = 'test fail';
        return $data;
    }
    

}

























